import Taro, { Component } from '@tarojs/taro'
import { AtTabs, AtTabsPane } from 'taro-ui'
import { View, ScrollView } from '@tarojs/components'
import { DNavBar, DCarship, DItemError, DModal } from '@/components'
import http from '@/api'
import './shiporder.scss'
const conf = require('../../../config/conf')

export default class Shiporder extends Component {
  constructor(props) {
    super(props)
    this.state = {
      active: 0,
      userStatus: 1, // 1:卖家 2:买家
      page: 1,
      limit: 10,
      totalPage: 1,
      list: [],
      isShow: false,
      modal1: '',
      footerStatus: false,
      scrollHeight: window.screen.availHeight,
      listStatus: false
    }
  }


  componentWillMount() {
    let { active = 0, remark, id } = this.$router.params
    if (remark == 2) {
      // 确认退款回调
      http.getBackOrder({ id }).then(res => {
        return Taro.redirectTo({
          url: `/pages/shiporder/shiporder?active=3`
        })
      })
      return
    }
    this.handleClick(+active)
  }

  componentDidShow() {
    let { listStatus } = this.state

    if (listStatus) {
      return
    }
    this.setState({
      list: [],
      footerStatus: false,
      page: 1,
      limit: 10,
      totalPage: 1,
      listStatus: true
    }, () => {
      if (this.state.active == 4) {
        this.pendingRefund2()
        return
      }
      this.getListInfo()
    })
  }

  getFirstBtn(active) {
    return {
      $21: '拒绝接单',
      $31: '',
      $41: '上传合同',
      $49: '确认合同',
      $59: '确认退款',
    }[`$${active}`]
  }
  getStatus(status) {
    return {
      $21: '待接单',
      $31: '待上传',
      $32: '待托运方确认',
      $41: '待上传',
      $42: '待托运方确认',
      $43: '待核实',
      $51: '交易成功',
      $52: '已拒接',
      $53: '已撤回',
      $54: '已超时',
      $55: '交易异常',
      $59: '待退款',
    }[`$${status}`]
  }
  getLasrBtn(active) {
    return {
      $21: '接受订单',
      $31: '上传验车'
    }[`$${active}`]
  }

  getListInfo() {
    let { active, page, limit, totalPage } = this.state
    if (page > totalPage) {
      this.setState({
        footerStatus: true
      })
      return
    }
    let _obj = {
      page,
      limit,
      status: active + 2
    }
    http.getOrderTransList(_obj).then(res => {
      let list = res.list
      let _list = []

      if (active === 0) {
        list = list.filter(item => item.orStatus == 21)
      }

      list.map(item => {
        _list.push({
          id: item.id,
          order: item.orNo,
          status: this.getStatus(item.orStatus),
          card: item.cdCarType.split('#')[0],
          data: item.createTime.split(' ')[0],
          addre: item.orSaleComp,
          beginaddre: item.cdStartAddr,
          endaddre: item.cdEndAddr,
          money: item.orPrice,
          orStatus: item.orStatus,
          firstText: this.getFirstBtn(item.orStatus) || '查看订单',
          lastText: this.getLasrBtn(item.orStatus)
        })
      })

      this.setState({
        list: [...this.state.list, ..._list],
        totalPage: res.totalPage,
        listStatus: false
      })
    })
  }

  onHandleDetail(item) {
    Taro.navigateTo({
      url: `/pages/itemdetail/itemorder?id=${item.id}&status=${item.orStatus}`
    })
  }
  onHandleFirst(item) {
    this.setState({
      id: item.id
    })
    if (item.firstText === '拒绝接单') {
      let isShow = true
      this.setState({
        isShow,
        crmodal: '2',
        modal1: '您确认拒绝接单吗？'
      })
    }
    else if (item.firstText === '下载合同') {
      http.htwlTemplate(item.id).then(res => {
        // 下载合同接口
        const a = document.createElement('a');
        const url = res.data;
        const filename = '车辆运输合同';
        a.href = url;
        a.download = filename;
        a.click();
      })
    }
    else if (item.firstText === '上传合同') {
      Taro.navigateTo({
        url: `/pages/caruploadtran/caruploadtran?id=${item.id}&orNo=${item.order}`
      })
    }
    else if (item.firstText === '查看订单') {
      Taro.navigateTo({
        url: `/pages/itemdetail/itemorder?id=${item.id}&status=${item.orStatus}`
      })
    }
    else if (item.firstText === '确认退款') {
      http.withdrawalOfConsent2(item.id).then((res) => {
        if (res === 0) {
          Taro.showToast({
            title: "该订单已退款",
            icon: "none",
            duration: 800
          });
          setTimeout(() => {
            Taro.redirectTo({
              url: "/pages/shiporder/shiporder?active=4"
            })
          }, 800);
        } else {
          this.setState({
            isShow: true,
            crmodal: '3',
            refundOrderId: item.id,
            modal1: '您是否确认退款？'
          })
        }
      })
    }
  }

  confirmMyList(id) { //接受订单
    http.confirmMyList(id).then(res => {
      Taro.navigateTo({
        url: `/pages/itemdetail/itemorder?id=${id}&status=33`
      })
    })
  }
  onClose() {
    this.setState({
      isShow: false
    })
  }
  async onLastHandle() {
    let { crmodal, id, refundOrderId } = this.state
    this.onClose()
    if (crmodal === '1') {
      this.confirmMyList(id)
    }
    if (crmodal === '2') {
      this.cancelMyList(id)
    }
    if (crmodal === '3') {
      http.withdrawalOfConsentTans(refundOrderId).then(({ infoData, bodyData, signData }) => {
        this.setState({
          infoData,
          bodyData,
          signData
        }, () => {
          this.refs.submit.click()
        })
      })
    }
  }

  confirmMyList(id) { //接受订单
    http.confirmMyList({ id }).then(res => {
      Taro.navigateTo({
        url: `/pages/itemdetail/itemorder?id=${id}&status=31`
      })
    })
  }

  onHandleLast(item) {
    this.setState({
      id: item.id
    })
    if (item.lastText === '接受订单') {
      let isShow = true
      this.setState({
        isShow,
        crmodal: '1',
        modal1: '您确认接受订单吗？'
      })
    }
    else if (item.lastText === '上传验车') {
      Taro.navigateTo({
        url: `/pages/deliveryupload/deliveryupload?id=${item.id}&orNo=${item.order}`
      })
    }
  }


  onScrollEnd = () => {
    this.setState({
      page: this.state.page + 1
    }, () => {
      this.getListInfo()
    })
  }


  getOrderTransList() {
    let obj = {
      limit: 10,
      page: 1,
      status: 5
    }
    http.getOrderTransList(obj).then(res => {
    })
  }

  refuseOrderTrans() {
    http.refuseOrderTrans({ id: `` }).then(res => {

    })
  }

  acceptOrderTrans() {
    http.acceptOrderTrans({ id: `` }).then(res => {

    })
  }
  cancelMyList(id) {  //拒绝接单
    http.cancelMyList2({ id }).then(res => {
      Taro.redirectTo({
        url: '/pages/shiporder/shiporder?active=4'
      })
    })
  }
  confirmMyList(id) { //接受订单
    http.confirmMyList({ id }).then(res => {
      Taro.navigateTo({
        url: `/pages/itemdetail/itemorder?id=${id}&status=31`
      })
    })
  }
  async pendingRefund2() {
    let { list } = await http.pendingRefund2()
    list = list.map(item => {
      return {
        ...item,
        id: item.id,
        order: item.orNo,
        status: this.getStatus(item.orStatus),
        card: item.cdCarType.split('#')[0],
        data: item.createTime.split(' ')[0],
        addre: item.orSaleComp,
        beginaddre: item.cdStartAddr,
        endaddre: item.cdEndAddr,
        money: item.orPrice,
        orStatus: item.orStatus,
        firstText: this.getFirstBtn(item.orStatus) || '查看订单',
      }
    })
    this.setState({
      list
    })
  }
  handleClick(value) {
    // 点击确认退款 tab
    if (value === 4) {
      this.pendingRefund2()
      this.setState({
        active: value
      })
      return
    }
    this.setState({
      list: [],
      footerStatus: false,
      active: value,
      page: 1,
      limit: 10,
      totalPage: 1,
      listStatus: true
    }, () => {
      this.getListInfo()
    })
  }
  render() {
    const tabList = [{ title: '待接单' }, { title: '待验车' }, { title: '待上传' }, { title: '已完结' }, { title: '确认退款' }]
    const {
      active,
      list,
      scrollHeight,
      footerStatus,
      isShow,
      modal1,
      infoData,
      bodyData,
      signData,
    } = this.state
    return (
      <View className='b_shiporder'>
        <DNavBar title={'承运订单'} className='b_shiporder_nav'></DNavBar>
        <View className='b_shiporder__box'>
          <View className='b_shiporder__content'>
            <AtTabs current={active} tabList={tabList} onClick={this.handleClick.bind(this)}>
              {
                tabList.map(tap => <AtTabsPane>
                  {
                    list.length > 0 && <ScrollView
                      scrollY
                      scrollWithAnimation
                      lowerThreshold='20'
                      style={`height:${scrollHeight - 100}PX`}
                      onScrollToLower={this.onScrollEnd}
                    >
                      {
                        list && list.map((item, i) => {
                          return <DCarship
                            onHandleDetail={this.onHandleDetail.bind(this, item)}
                            // status={tap.title}
                            {...item}
                            onHandleFirst={this.onHandleFirst.bind(this, item)}
                            onHandleLast={this.onHandleLast.bind(this, item)}
                          >
                          </DCarship>
                        })
                      }
                      {
                        footerStatus && <View className='b_shiporder__more'>暂无更多</View>
                      }
                    </ScrollView>
                  }
                </AtTabsPane>)
              }

            </AtTabs>
          </View>
        </View>
        {
          list.length === 0 && <DItemError></DItemError>
        }
        <DModal
          isShow={isShow}
          title='提示'
          text={modal1}
          firstbtn='取消'
          lastbtn='确认'
          onFirst={this.onClose.bind(this)}
          onCancel={this.onClose.bind(this)}
          onLast={this.onLastHandle.bind(this)}
        ></DModal>

        {/* 跳转龙存管页面 */}
        <form action={conf.fromURL} method="post">
          <input type="hidden" name="INFO" value={infoData} />
          <input type="hidden" name="CONTENTTYPE" value="json" />
          <input type="hidden" name="charset" value="GBK" />
          <input type="hidden" name="BODY" value={bodyData} />
          <input type="hidden" name="SIGN" value={signData} />
          <input type="submit" ref="submit" value="Submit" style={{ opacity: 0, width: 0, height: 0 }} />
        </form>
      </View >

    )
  }
}
